let hiddenTextarea = null;

const HIDDEN_STYLE = `
  position:absolute !important;
  height:0 !important;
  overflow:hidden !important;
  top:0 !important;
  right:0 !important;
  z-index:-1000 !important;
  visibility:hidden !important;`;

const CONTEXT_STYLE = [
  'letter-spacing',
  'line-height',
  'padding-top',
  'padding-bottom',
  'font-family',
  'font-weight',
  'font-size',
  'text-rendering',
  'text-transform',
  'width',
  'text-indent',
  'padding-left',
  'padding-right',
  'border-width',
  'box-sizing',
];

function calculateNodeStyling(targetElement) {
  const style = window.getComputedStyle(targetElement);
  const paddingSize = (parseFloat(style.getPropertyValue('padding-bottom')) + parseFloat(style.getPropertyValue('padding-top')));
  const contextStyle = CONTEXT_STYLE.map((name) => {
    return `${name}:${style.getPropertyValue(name)}`;
  }).join(';');
  return {
    contextStyle,
    paddingSize,
  };
}

export default function modifyTextareaHeight(
  targetElement,
  minRows = null,
  maxRows = null,
) {
  if (!hiddenTextarea) {
    hiddenTextarea = document.createElement('textarea');
    document.body.appendChild(hiddenTextarea);
  }
  const {
    contextStyle,
    paddingSize,
  } = calculateNodeStyling(targetElement);
  hiddenTextarea.setAttribute('style', `${contextStyle};${HIDDEN_STYLE}`);
  hiddenTextarea.value = targetElement.value || targetElement.placeholder || '';
  let height = hiddenTextarea.scrollHeight - paddingSize;
  hiddenTextarea.value = '';
  const singleRowHeight = hiddenTextarea.scrollHeight - paddingSize;
  if (minRows != null) {
    const minHeight = singleRowHeight * minRows;
    height = Math.max(minHeight, height);
  }
  if (maxRows != null) {
    const maxHeight = singleRowHeight * maxRows;
    height = Math.min(maxHeight, height);
  }
  height += paddingSize;
  let width = window.innerWidth;
  if (width < 1200) {
    width = 1200;
  }
  const remFs = width / 50;
  return { height: `${height / remFs}rem` };
}
